package org.eden.rpc.core.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import org.eden.rpc.common.entity.RpcRequest;
import org.eden.rpc.common.entity.RpcResponse;
import org.eden.rpc.common.enumerate.ErrorCode;
import org.eden.rpc.common.enumerate.PackageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class DefaultDecoder extends ReplayingDecoder<Void> {

    private static final int MAGIC_NUMBER = 0xCAFEBABE;

    private static final Logger logger = LoggerFactory.getLogger(DefaultDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magic = in.readInt();
        if (magic != MAGIC_NUMBER) {
            logger.error("不认识的协议包: {}", magic);
            throw new RuntimeException(ErrorCode.UNKNOWN_PROTOCOL.getMsg());
        }

        int packageType = in.readInt();
        Class<?> packageClass;
        if (packageType == PackageType.REQUEST_PACKAGE.getType()) {
            packageClass = RpcRequest.class;
        } else if (packageType == PackageType.RESPONSE_PACKAGE.getType()) {
            packageClass = RpcResponse.class;
        } else {
            logger.error("不认识的数据包: {}", packageType);
            throw new RuntimeException(ErrorCode.UNKNOWN_PACKAGE_TYPE.getMsg());
        }

        int serializerCode = in.readInt();
        Serializer serializer = Serializer.getInstance(serializerCode);
        if (serializer == null) {
            logger.error("不认识的序列化器");
            throw new RuntimeException(ErrorCode.UNKNOWN_SERIALIZER.getMsg());
        }

        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        out.add(serializer.deserialize(bytes, packageClass));
    }
}
